package com.trs.publish.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import com.trs.publish.domain.Power;
import com.trs.publish.repository.PowerRepository;
import com.trs.publish.repository.UserRepository;

@Component  
public class CustomUserDetailsService implements UserDetailsService {  

		@Autowired
		private UserRepository userRepository;
		
		@Autowired
		private PowerRepository powerRepository;
		
		//重写loadUserByUsername 方法获得 userdetails 类型用户
	    @Override
	    public UserDetails loadUserByUsername(String username) { 

	        com.trs.publish.domain.User user = userRepository.findByName(username);	        
	        if(user == null){
	        	throw new UsernameNotFoundException(username+": 用户名不存在");
	        }
	       
	        //根据用户获取权限
	        String roles = user.getRole();
	        List<String> rolesList = new ArrayList<String>();
	        if(StringUtils.isNoneEmpty(roles)) {
	        	for(String role:roles.split(",")) {
	        		if(StringUtils.isNoneEmpty(role)) {
	        			rolesList.add(role);
	        		}
	        	}
	        }
	        List<Power> permissions = new ArrayList<Power>();
	        
	      //定义权限集合  
	        Collection<GrantedAuthority> grantedAuths = new ArrayList<GrantedAuthority>(); 
	        if(rolesList!=null&&rolesList.size()>0) {
	        	 permissions = powerRepository.getRolesPowers(rolesList);
	        	 //添加权限到集合中  
	 	        for (Power permission: permissions){  
	 	                GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permission.getPowername());  
	 	                grantedAuths.add(grantedAuthority);  
	 	        } 
	        }
	        //将已登录的用户信息保存到SecurityContext  
	        org.springframework.security.core.userdetails.User userDetail = new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(), true, true, true, true, grantedAuths); 
	        return userDetail;  
	    }
}